package com.LCQ.crm.workbench.service.impl;

import com.LCQ.crm.exception.ClueConvertException;
import com.LCQ.crm.exception.ClueDeleteException;
import com.LCQ.crm.utils.DateTimeUtil;
import com.LCQ.crm.utils.SqlSessionUtil;
import com.LCQ.crm.utils.UUIDUtil;
import com.LCQ.crm.vo.PaginationVo;
import com.LCQ.crm.workbench.dao.*;
import com.LCQ.crm.workbench.domain.*;
import com.LCQ.crm.workbench.service.ClueService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ClueServiceImpl implements ClueService {
    private ClueDao clueDao = SqlSessionUtil.getSqlSession().getMapper(ClueDao.class);
    private ClueRemarkDao clueRemarkDao = SqlSessionUtil.getSqlSession().getMapper(ClueRemarkDao.class);
    private ClueActivityRelationDao clueActivityRelationDao = SqlSessionUtil.getSqlSession().getMapper(ClueActivityRelationDao.class);
    private ActivityDao activityDao = SqlSessionUtil.getSqlSession().getMapper(ActivityDao.class);
    private CustomerDao customerDao = SqlSessionUtil.getSqlSession().getMapper(CustomerDao.class);
    private CustomerRemarkDao customerRemarkDao = SqlSessionUtil.getSqlSession().getMapper(CustomerRemarkDao.class);
    private ContactsDao contactsDao = SqlSessionUtil.getSqlSession().getMapper(ContactsDao.class);
    private ContactsRemarkDao contactsRemarkDao = SqlSessionUtil.getSqlSession().getMapper(ContactsRemarkDao.class);
    private ContactsActivityRelationDao contactsActivityRelationDao  = SqlSessionUtil.getSqlSession().getMapper(ContactsActivityRelationDao.class);
    private TranDao tranDao  = SqlSessionUtil.getSqlSession().getMapper(TranDao.class);
    private TranHistoryDao tranHistoryDao  = SqlSessionUtil.getSqlSession().getMapper(TranHistoryDao.class);

    @Override
    public boolean save(Clue clue) {
        int result = clueDao.insert(clue);
        return result==1;
    }

    @Override
    public PaginationVo<Clue> getPageList(Map<String, Object> map) {
        PaginationVo<Clue> page = new PaginationVo<>();
        page.setTotal(clueDao.getCountByCondition(map));
        page.setPageList(clueDao.getListByCondition(map));
        return page;
    }

    @Override
    public Clue getClueById(String id) {
        return clueDao.getById(id);
    }

    @Override
    public List<Map> getAssociatedAct(String id) {
        return clueActivityRelationDao.getActByClueId(id);
    }

    @Override
    public boolean unbindActCLue(String id) {
        int result = clueActivityRelationDao.delete(id);
        return result==1;
    }

    @Override
    public PaginationVo getUnbindingActByCond(Map<String, String> map) {
        PaginationVo<Activity> page = new PaginationVo<>();
        List<Activity> list = activityDao.getUnbindingActByCond(map);
        page.setPageList(list);
        page.setTotal(list.size());
        return page;
    }

    @Override
    public boolean bindActClue(String clueId,String[] actIds) {
        List<ClueActivityRelation> list = new ArrayList<>();
        for(int i=0; i<actIds.length; i++){
            ClueActivityRelation c = new ClueActivityRelation();
            c.setId(UUIDUtil.getUUID());
            c.setClueId(clueId);
            c.setActivityId(actIds[i]);
            list.add(c);
        }

        int result = clueActivityRelationDao.inserts(list);
        return result==list.size();
    }

    @Override
    public List<Activity> getBindActByCond(Map map) {
        return activityDao.getByClueAName(map);
    }

    @Override
    public boolean delete(String clueId) throws ClueDeleteException {
        int relationCount = clueActivityRelationDao.getCountByClueId(clueId);
        int count = clueActivityRelationDao.deleteByClueId(clueId);
        if(count!=relationCount){
            throw new ClueDeleteException("删除线索活动关系信息失败");
        }
        int remarkCount = clueRemarkDao.getCountByClueId(clueId);
        count = clueRemarkDao.deleteByClueId(clueId);
        if(count!=remarkCount){
            throw new ClueDeleteException("删除线索备注信息失败");
        }
        count = clueDao.delete(clueId);
        return true;
    }

    @Override
    public boolean convert(String clueId, Tran tran, String createBy) throws ClueConvertException {
        Clue clue = clueDao.getByIdActual(clueId);
        if(clue==null){
            throw new ClueConvertException("线索ID不存在");
        }

        String clueCompany = clue.getCompany();
        if(clueCompany==null||clueCompany==""){
            throw new ClueConvertException("公司信息为空");
        }

        Customer customer = customerDao.getByName(clueCompany);
        if(customer==null){
            //创建客户
            customer = new Customer();
            customer.setAddress(clue.getAddress());
            customer.setContactSummary(clue.getContactSummary());
            customer.setCreateBy(createBy);
            customer.setCreateTime(DateTimeUtil.getSysTime());
            customer.setDescription(clue.getDescription());
            customer.setId(UUIDUtil.getUUID());
            customer.setName(clueCompany);
            customer.setNextContactTime(clue.getNextContactTime());
            customer.setOwner(clue.getOwner());
            customer.setPhone(clue.getPhone());
            int count1 = customerDao.insert(customer);
            if(count1!=1){
                throw new ClueConvertException("客户信息添加失败");
            }
        }

        //创建联系人
        Contacts contacts = new Contacts();
        contacts.setAddress(clue.getAddress());
        contacts.setAppellation(clue.getAppellation());
        contacts.setContactSummary(clue.getContactSummary());
        contacts.setCreateBy(createBy);
        contacts.setCreateTime(DateTimeUtil.getSysTime());
        contacts.setCustomerId(customer.getId());
        contacts.setDescription(clue.getDescription());
        contacts.setEmail(clue.getEmail());
        contacts.setFullname(clue.getFullname());
        contacts.setJob(clue.getJob());
        contacts.setMphone(clue.getMphone());
        contacts.setNextContactTime(clue.getNextContactTime());
        contacts.setNextContactTime(clue.getNextContactTime());
        contacts.setSource(clue.getSource());
        contacts.setOwner(clue.getOwner());
        contacts.setId(UUIDUtil.getUUID());
        int count2 = contactsDao.insert(contacts);
        if(count2!=1){
            throw new ClueConvertException("联系人信息添加失败");
        }

        //添加客户备注
        List<ClueRemark> listClueRk = clueRemarkDao.getRemarkByClueId(clueId);
        if(listClueRk.size()>0){
            List<CustomerRemark> listCusRk = new ArrayList<>();
            for (int i=0;i<listClueRk.size();i++){
                ClueRemark clueRemark = listClueRk.get(i);
                CustomerRemark customerRemark = new CustomerRemark();
                customerRemark.setCreateBy(createBy);
                String sysTime = DateTimeUtil.getSysTime();
                customerRemark.setCreateTime(sysTime);
                customerRemark.setEditTime(sysTime);
                customerRemark.setCustomerId(customer.getId());
                customerRemark.setEditFlag("0");
                customerRemark.setNoteContent(clueRemark.getNoteContent());
                customerRemark.setId(UUIDUtil.getUUID());
                listCusRk.add(customerRemark);
            }
            int count3 = customerRemarkDao.inserts(listCusRk);
            if(count3!=listCusRk.size()){
                throw new ClueConvertException("客户备注信息添加失败");
            }

            //添加联系人备注
            List<ContactsRemark> listContactRk = new ArrayList<>();
            for (int i=0;i<listClueRk.size();i++){
                ClueRemark clueRemark = listClueRk.get(i);
                ContactsRemark contactsRemark = new ContactsRemark();
                contactsRemark.setContactsId(contacts.getId());
                contactsRemark.setCreateBy(createBy);
                String sysTime = DateTimeUtil.getSysTime();
                contactsRemark.setCreateTime(sysTime);
                contactsRemark.setEditTime(sysTime);
                contactsRemark.setEditFlag("0");
                contactsRemark.setId(UUIDUtil.getUUID());
                contactsRemark.setNoteContent(clueRemark.getNoteContent());
                listContactRk.add(contactsRemark);
            }

            int count4 = contactsRemarkDao.inserts(listContactRk);
            if(count4!=listContactRk.size()){
                throw new ClueConvertException("客户备注信息添加失败");
            }
        }

        //添加联系人活动关系
        List<ClueActivityRelation> listClueActRelation = clueActivityRelationDao.getByClueId(clueId);
        if(listClueActRelation.size()>0){
            List<ContactsActivityRelation> listContactActRel = new ArrayList<>();
            for(int i=0;i<listClueActRelation.size();i++){
                ClueActivityRelation clueActivityRelation = listClueActRelation.get(i);
                ContactsActivityRelation contactsActivityRelation = new ContactsActivityRelation();
                contactsActivityRelation.setContactsId(contacts.getId());
                contactsActivityRelation.setActivityId(clueActivityRelation.getActivityId());
                contactsActivityRelation.setId(UUIDUtil.getUUID());
                listContactActRel.add(contactsActivityRelation);
            }
            int count5 = contactsActivityRelationDao.inserts(listContactActRel);
            if(count5!=listContactActRel.size()){
                throw new ClueConvertException("联系人活动关系信息添加失败");
            }
        }

        //创建交易
        if(tran != null){
            tran.setContactsId(contacts.getId());
            tran.setContactSummary(contacts.getContactSummary());
            tran.setCreateBy(createBy);
            String sysTime = DateTimeUtil.getSysTime();
            tran.setCreateTime(sysTime);
            tran.setEditTime(sysTime);
            tran.setCustomerId(customer.getId());
            tran.setDescription(clue.getDescription());
            tran.setId(UUIDUtil.getUUID());
            tran.setOwner(clue.getOwner());
            tran.setSource(clue.getSource());
            int count6 = tranDao.insert(tran);
            if(count6!=1){
                throw new ClueConvertException("添加交易信息失败");
            }

            TranHistory tranHistory = new TranHistory();
            tranHistory.setCreateBy(createBy);
            tranHistory.setCreateTime(DateTimeUtil.getSysTime());
            tranHistory.setExpectedDate(tran.getExpectedDate());
            tranHistory.setId(UUIDUtil.getUUID());
            tranHistory.setMoney(tran.getMoney());
            tranHistory.setStage(tran.getStage());
            tranHistory.setTranId(tran.getId());
            int count7 = tranHistoryDao.insert(tranHistory);
            if(count7!=1){
                throw new ClueConvertException("添加交易历史信息失败");
            }
        }

        //删除线索信息
        try {
            delete(clueId);
        } catch (Exception e) {
            throw new ClueConvertException(e.getMessage());
        }

        return true;
    }
}
